<style>
  .logo {
    width: 30px;
    height: 30px;
    border-radius: 50px;
  }
</style>
<div class="layui-header">
  <div class="layui-logo layui-hide-xs layui-bg-black">
    <img src="" alt="" id="logo" class="logo" />
    <span id="logoText">明德后台管理系统</span>
  </div>
  <!-- 头部区域（可配合layui 已有的水平导航） -->

  <ul class="layui-nav layui-layout-left">
    <!-- 移动端显示 -->
    <li
      class="layui-nav-item layui-show-xs-inline-block layui-hide-sm"
      lay-header-event="menuLeft"
    >
      <i class="layui-icon layui-icon-spread-left"></i>
    </li>

    <li class="layui-nav-item layui-hide-xs"><a href="">教务端</a></li>
    <li class="layui-nav-item layui-hide-xs"><a href="">师生端</a></li>
    <li class="layui-nav-item layui-hide-xs"><a href="">共享端</a></li>
    <li class="layui-nav-item">
      <a href="javascript:;">Nav groups</a>
      <dl class="layui-nav-child">
        <dd><a href="">1111</a></dd>
        <dd><a href="">menu 22</a></dd>
        <dd><a href="">menu 33</a></dd>
      </dl>
    </li>
  </ul>
  <ul class="layui-nav layui-layout-right">
    <li class="layui-nav-item layui-hide layui-show-md-inline-block">
      <a href="javascript:;" id="addLogo">系统编辑</a>
    </li>
    <li class="layui-nav-item layui-hide layui-show-md-inline-block">
      <a
        >帳號:{{userInfo.username}} 上一次登入时间：{{userInfo.last_login_date |
        dealDate 'YYYY-MM-DD'}}</a
      >
    </li>

    <li class="layui-nav-item layui-hide layui-show-md-inline-block">
      <a href="javascript:;">
        <img id="preview" src="/{{userInfo.avater}}" class="layui-nav-img" />
      </a>
      <dl class="layui-nav-child">
        <dd><a href="">个人信息</a></dd>
        <dd><a href="javascript:;" id="updAvatar">更改头像</a></dd>
        <input type="file" id="avatarFile" style="display: none" />
        <dd><a href="javascript:;" id="updatePassword">修改密码</a></dd>
        <dd><a href="javascript:void(0)" onclick="logout()">退出</a></dd>
      </dl>
    </li>
    <li class="layui-nav-item" lay-header-event="menuRight" lay-unselect>
      <a href="javascript:;">
        <i class="layui-icon layui-icon-more-vertical"></i>
      </a>
    </li>
  </ul>
</div>
<script src="https://momentjs.bootcss.com/downloads/moment.min.js"></script>
<script src="/static/js/jquery.js"></script>
<script src="/static/layui-v2.6.8/layui/layui.js"></script>
<script>
  window.onload = function () {
    // 修改密码
    // 弹窗修改密码的模板
    let htmlStr = `
            <div id="updPasswordContainer">
          <div class="layui-form-item">
            <label class="layui-form-label">原密码</label>
            <div class="layui-input-inline">
              <input type="password" id="oldpassword"   placeholder="请输入新密码" class="layui-input" autocomplete="off" >
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">新密码</label>
            <div class="layui-input-inline">
              <input type="password" id="password"  placeholder="请输入新密码" autocomplete="off" class="layui-input">
            </div>
          </div>
          <div class="layui-form-item">
            <label class="layui-form-label">确认新密码</label>
            <div class="layui-input-inline">
              <input type="password" id="repassword"  placeholder="请输入新密码" autocomplete="off" class="layui-input">
            </div>
          </div>
        </div>
      `;

    $("#updatePassword").click(function () {
      //页面层
      layer.open({
        title: "修改密码",
        shadeClose: true,
        skin: "layui-layer-rim", //加上边框
        area: ["520px", "340px"], //宽高
        content: htmlStr,
        btn: "确认修改",
        yes: function (index, layero) {
          //按钮的回调
          console.log("55555");
          // 获取三个密码
          let oldpwd = $("#oldpassword").val();
          let newpwd = $("#password").val();
          let renewpwd = $("#repassword").val();
          console.log(oldpwd, newpwd, renewpwd);
          if ([oldpwd, newpwd, renewpwd].includes("")) {
            alert("不能为空");
            return;
          }
          if (newpwd !== renewpwd) {
            alert("两次密码不一致");
            return;
          }
          //发送ajax请求 进行更换密码
          let xhr = new XMLHttpRequest();
          xhr.onreadystatechange = function () {
            if (this.readyState === 4 && this.status === 200) {
              let { code, message } = JSON.parse(this.responseText);
              if (code === 20000) {
                layer.msg(message);
                location.href = "/logout";
              } else {
                alert(message);
              }
            }
          };
          xhr.open("post", "/updatePassword", true);
          xhr.setRequestHeader(
            "Content-type",
            "application/x-www-form-urlencoded"
          );
          let formData = `oldpwd=${oldpwd}&newpwd=${newpwd}&renewpwd=${renewpwd}`;
          xhr.send(formData);
        },
      });
    });

    // 发送ajax请求修改密码(要用委托去绑定)
    // 原因： 因为弹窗中的按钮是属于动态新增的元素，对于新增只能用委托为来完成绑定。
  };
  console.log();
  document.getElementById("logo").src = localStorage.getItem("blog_logo");

  document.getElementById("addLogo").onclick = async function () {
    let { data } = await $.get("/systemData");
    console.log(data);
    data = data.map((item) => {
      return item.val;
    });
    oldPic = data[0];
    layer.open({
      type: 1,
      area: ["550px", "300px"],
      content: `
      <form class="layui-form" id="myform" lay-filter="editform">
          <div>
              <div class="layui-form-item">
                <label class="layui-form-label">上传logo：</label>
                <div class="layui-input-block">
                  <div class="layui-upload" style="position: relative;">
                    <input type="file" name="blogLogo" style="display:none;" onchange="uploads(this)">
                    <div class="layui-upload-list drag-disabled" style="display:inline-block;">
                      <img class="layui-upload-img" id="blogLogo" src="${data[1]}"
                        style="display: block;width:80px;height:80px;border-radius:50px;" draggable="false">
                    </div>
                    <button type="button" class="layui-btn" id="test1"
                      style="position: absolute;right: 256px;top: 10px;">更换Logo</button>
                    <span style="position: absolute;top: 60px;">支持JPG、PNG、GIF格式，小于2MB</span>
                  </div>
                </div>
              </div>
              <div class="layui-form-item" style="position: relative;text-align:center">
                  <button type="submit" class="layui-btn" lay-submit="" lay-filter="blogInfo"
                    style="">立即提交</button>
                
              </div>
            </div>
          </div>
        </form>
      `, //这里content是一个普通的String
    });
  };
  // const layer = layui.layer,form = layui.form;
  let settingPic = true;
  function uploads(ele) {
    settingPic = ele.files[0];
    if (settingPic) {
      let filereader = new FileReader();
      filereader.readAsDataURL(settingPic);
      let fileName = settingPic.name;
      let fileExt = fileName.lastIndexOf(".");
      let fileSuffix = fileName.substring(fileExt + 1, fileName.length);
      // 单位换算： 1GB = 1024MB , 1MB = 1024KB  1kb = 1024byte
      let fileSize = Math.ceil(settingPic.size / 1024 / 1024);
      filereader.onload = function () {
        if (
          fileSize < 2 &&
          (fileSuffix === "jpg" || fileSuffix === "png" || fileSuffix === "gif")
        ) {
          $("#blogLogo").attr("src", this.result);
          settingPic = true;
        } else {
          layer.msg("请上传正确格式的图片，不大于2MB的图片。", { icon: 2 });
          settingPic = false;
        }
      };
    }
  }

  let oldPic;
  layui.use(["table", "util", "form"], async function () {
    var table = layui.table,
      util = layui.util,
      $ = layui.jquery,
      form = layui.form;

    form.on("submit(blogInfo)", function (data) {
      let myForm = $("#myform")[0];
      let formData = new FormData(myForm);

      formData.set("oldPic", oldPic);
      // 有上传图片则删除原图  反之保留原图
      if (settingPic) {
        $.ajax({
          type: "post",
          url: `/updsystemData`,
          data: formData,
          processData: false,
          contentType: false,
        }).then((res) => {
          let { err, msg, pic } = res;
          err == "20000"
            ? (layer.msg(msg, { icon: 1 }), location.reload())
            : layer.msg(msg, { icon: 2 });
          localStorage.setItem("blog_logo", pic);
        });
      } else {
        layer.msg("请更换正确格式的图片。");
      }

      return false; // 这句话阻止默认行为 会包装成一个Promise.resove(false)进行返回
    });

    // 点击上传文件自行点击上传文件
    $(document).on("click", "#test1", function () {
      $("input[name=blogLogo]").eq(0).click();
    });
  });

  // 退出
  function logout() {
    if (confirm("确认退出吗")) {
      location.href = "/logout";
    }
  }

  // ajax 更新用户头像
  let avatarFile = document.getElementById("avatarFile");
  let preview = document.getElementById("preview");
  document.getElementById("updAvatar").onclick = function () {
    // 执行input文件框单击事件
    avatarFile.click();
  };

  // 给文件绑定onchange事件，来判断用户是否上传了文件
  avatarFile.onchange = function () {
    let file = this.files[0]; // 获取文件的二进制数据
    if (!file) {
      return;
    }
    let formData = new FormData();
    formData.append("avater", file);

    let xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
      if (this.readyState === 4 && this.status === 200) {
        let data = JSON.parse(this.responseText);
        let { message, code, src } = data;
        if (code === 20000) {
          layer.msg(message, { icon: 1, time: 1000 });
          // 把服务器返回的图片路径设置img的src中，实现图片预览
          preview.src = "/" + src;
        } else {
          layer.msg(message);
        }
      }
    };
    xhr.open("post", "/uploadAvatar", true);
    xhr.send(formData);
  };
</script>
